import 'dart:async';
import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/nodeSpeed/nodeSpeed.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import '../../../module_common/provider/nav_key.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/router/app_route_page_utils.dart';
import '../model/assets_model.dart';

import '../provider/wallet_node_provider.dart';

// 快，慢，繁忙
enum NewWorkStatus { green, red, warn }

class AssetsNetworkWidget extends StatefulWidget {
  final Chain? chain;
  final Function onClick;

  AssetsNetworkWidget({super.key, this.chain, required this.onClick});

  @override
  State<StatefulWidget> createState() {
    return _AssetsNetworkWidgetState();
  }
}

class _AssetsNetworkWidgetState extends State<AssetsNetworkWidget> with RouteAware {
  Color networkColor = Color.fromRGBO(190, 189, 202, 1);
  late StreamSubscription walletSubscription;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      startTimer();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    /// 路由订阅
    AppRouterPageUtils().routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  // 监听路由 当每次返回当前页面刷新 initStatus
  @override
  void didPopNext() {
    super.didPopNext();
    // 在这里处理页面返回事件
    if (ModalRoute.of(context)!.isCurrent) {
      startTimer();
    } else{
      startTimer(isReturn: true);
    }
  }

  @override
  void didPushNext() {
    super.didPushNext();
    //从当前页面跳转到其他页面时调用
    if (ModalRoute.of(context)!.isCurrent) {
      startTimer();
    } else{
      startTimer(isReturn: true);
    }
  }

  void startTimer({bool isReturn = false}) {
    if (AssetsPageModel().timer != null) {
      new AssetsPageModel().timer!.cancel();
    }
    if (isReturn) {
      return;
    }
    print('startTimer ${new AssetsPageModel().timer}');
    if(mounted)
    new AssetsPageModel().setTimer(Timer.periodic(Duration(seconds: 10), (timer) {
      if(mounted){
        Chain c = NavKey.getContext().read<WalletInfoNotifier>().walletChain!;
        if(c.shortName.isNotEmpty)
        context.read<NodeProvider>().updateNodeOne(chain:  c.shortName);
      }
    }));
  }

  @override
  void dispose() {
    if (new AssetsPageModel().timer != null) {
      new AssetsPageModel().setTimer(null);
    }

    /// 取消路由订阅
    AppRouterPageUtils().routeObserver.unsubscribe(this);
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GestureDetector(
      child: Consumer2<NodeProvider,WalletInfoNotifier>(builder: (c, provider,model, _) {
      final _chain = context.read<WalletInfoNotifier>().walletChain!;
      var _nodeItem = provider.getSelectedNodeInfo(chain: _chain.shortName);
      var rate = _nodeItem.blockHeight == '0' ? '0':(_nodeItem.rate??'0');
      return Container(
        color: Colors.transparent,
            child: NodeSpeed(
              color: NodeRateUtils.getCurrentRateColor(currentRate: rate),
            ),
            margin: EdgeInsets.only(right: 10.w),
        padding: EdgeInsets.only(left: 30.w),
          ) ;
      }),
      onTap: () {
        widget.onClick();
      },
    );
  }
}


class AssetsNodeNetworkWidget extends StatefulWidget {
  final Chain? chain;
  final bool? isRepeat;
  final Function onClick;

  // final NodeList node;
  // required this.node
  AssetsNodeNetworkWidget({super.key, this.chain, this.isRepeat, required this.onClick});

  @override
  State<StatefulWidget> createState() {
    return _AssetsNodeNetworkWidgetState();
  }
}

class _AssetsNodeNetworkWidgetState extends State<AssetsNodeNetworkWidget> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if(mounted)
      context.read<NodeProvider>().updateNodeOne(chain: widget.chain!.shortName);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GestureDetector(
      child:  Consumer<NodeProvider>(builder: (c, provider, _) {
        var _nodeItem = provider.getSelectedNodeInfo(chain: widget.chain!.shortName);
        var rate = _nodeItem.blockHeight=='0' ? '0':(_nodeItem.rate??'0');
        return  NodeSpeed(
          color: NodeRateUtils.getCurrentRateColor(currentRate: rate),
        );
          }
        ),
      onTap: () {
        // widget.onClick();
      },
    );
  }
}
